<?php
/**
 * 自定义模型基类(继承了关联模型)
 * 
 * @author:  will.lee <im.will.lee@gmail.com>
 * @version: 1.0
 */
class AppModel extends RelationModel
{
    // 验证规则列表
    protected $_validate_list = false;
    // 开启批量验证
    public $patchValidate  = true;
    
    /**
     * 插入数据前的回调方法
     */
    protected function _before_insert(&$data,$options)
    {
        $fields = $this->getDbFields();
        if(in_array('created',$fields) && !isset($data['created']))
        {
            $data['created'] = array('exp', 'NOW()');
        }
        if(in_array('created_id',$fields) && !isset($data['created_id']))
        {
            if(session('?'.C('ADMIN_SESSION_KEY')))
            {
                $login_info  = session(C('ADMIN_SESSION_KEY'));
                if(!empty($login_info))
                {
                    $data['created_id'] = $login_info['id'];
                }
            }
        }
    }
    
    /**
     * 更新数据前的回调方法
     */
    protected function _before_update(&$data,$options)
    {
        $fields = $this->getDbFields();
        if(in_array('modified',$fields) && !isset($data['modified']))
        {
            $data['modified'] = array('exp', 'NOW()');
        }
        if(in_array('modified_id',$fields) && !isset($data['modified_id']))
        {
            if(session('?'.C('ADMIN_SESSION_KEY')))
            {
                $login_info  = session(C('ADMIN_SESSION_KEY'));
                if(!empty($login_info))
                {
                    $data['modified_id'] = $login_info['id'];
                }
            }
        }
    }
    
    /**
     * 设置当前验证规则
     */
    public function setValidate($name)
    {
        if(isset($this->_validate_list[$name]))
        {
            $this->_validate = $this->_validate_list[$name];
        }
        else
        {
            throw_exception('未定义验证规则:'.$name);
        }
    }
    
    /**
     * 防止更新冲突
     */
    public function checkUpdateConflict($where)
    {
        $fields = $this->getDbFields();
        if(in_array('modified',$fields))
        {
            $result = $this->field($this->getPk())->where($where)->find();
            if(empty($result))
            {
                return false;
            }
        }
        return true;
    }
}